import { ForwardedRef, forwardRef, useRef, useEffect } from 'react';
import { connect, mapProps } from '@formily/react';
import { useEvents } from '@inbiz/utils';
// import { IPageInbiz } from '@inbiz/render';
// import {connect} from '@formily/react'
import cls from 'classnames';
import InBizTable from './Table';
import { useInbizPrefixCls, useIsDesigner } from '../../hooks';
import { InBizTableCtx, InBizTableRefCtx } from '../../context';
import TableDesigner from '../../designer/web/designer';
import { TablePreviewProps } from '../../interfaces';
import '../../style.less';

const TablePreview = (props: TablePreviewProps, ref: ForwardedRef<any>) => {
  const { emit, callBackEvents, prefixCls = 'subtable', zebraEffect,viewMode } = props;
  const tablePrefixCls = useInbizPrefixCls(prefixCls);
  const isDesigner = useIsDesigner();
  const searchRef = useRef({
    pageInfo: {
      pageSize: 999,
      current: 1,
    },
  });
  const firstRequestRef = useRef<boolean>(true);
  const pageRef = useRef<{ page: IPageInbiz }>(null);
  const [eventsRef] = useEvents(callBackEvents, emit);
  return (
    <div className={cls(`${tablePrefixCls}`, { 'inbiz-subTable-zebra': zebraEffect })}>
      <InBizTableRefCtx.Provider value={{ searchRef, eventsRef, firstRequestRef, pageRef }}>
        <InBizTableCtx.Provider value={{ ...props }}>
          {isDesigner ? (
            <TableDesigner {...props} ref={ref} />
          ) : (
            <InBizTable {...props} ref={ref} />
          )}
        </InBizTableCtx.Provider>
      </InBizTableRefCtx.Provider>
    </div>
  );
};

export default connect(
  forwardRef(TablePreview),
  mapProps({}, (props) => {
    const { formItems } = props.columnConfig || {};
    if (formItems?.actionDisplaySetup) {
      if (!formItems?.tableHeaderBtnShow) {
        formItems['tableHeaderBtnShow'] = formItems.actionDisplaySetup
      }
      if (!formItems?.inLineBtnShow) {
        formItems['inLineBtnShow'] = formItems.actionDisplaySetup
      }
    }
    return { ...props };
  }),
);
